package cn.denvie.agent;

import cn.denvie.agent.common.AgentContext;
import cn.denvie.agent.logger.JclLogger;
import cn.denvie.agent.logger.ILogger;
import cn.denvie.agent.utils.StringUtils;

import java.io.File;
import java.lang.instrument.Instrumentation;
import java.nio.file.FileSystems;

/**
 * 字节码插桩代理。
 *
 * @author DengZhaoyong
 * @version 1.0.0
 */
public class ByteAgent {

    private static ILogger logger = new JclLogger(ByteAgent.class.getName());

    // 插桩入口
    public static void premain(String argument, Instrumentation instrumentation) {
        logger.info("ByteAgent.premain() start, argument = " + argument);
        if (Boolean.getBoolean("agent.attached")) {
            // agent is already attached; don't attach twice
            // don't fail as this is a valid case
            // for example, Spring Boot restarts the application in dev mode
            return;
        }
        try {
            FileSystems.getDefault();
            // getAgentHome();

            // 初始化AgentContext
            AgentContext.init(argument, instrumentation);

            System.setProperty("agent.attached", Boolean.TRUE.toString());
        } catch (Exception e) {
            logger.error("Failed to start agent.\n");
            e.printStackTrace();
        }
        logger.info("ByteAgent.premain() end.\n");
    }

    private static File getAgentHome() {
        String file = ByteAgent.class.getProtectionDomain().getCodeSource().getLocation().getFile();
        if (StringUtils.isEmpty(file)) {
            return null;
        }
        final File agentJar = new File(file);
        logger.info("Agent home path: " + file);
        return agentJar.getAbsoluteFile();
    }

}
